package org.dwpd.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dwpd.utils.JwtEmailHelper;
import org.dwpd.domain.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Package:com.tong.interception
 *
 * @ClassName:EmailInterceptor
 * @Create:2024/5/9 21:07
 **/
@Component
public class EmailInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtEmailHelper jwtEmailHelper;

    //拦截器，验证码是否过期
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String code = request.getHeader("emailCode");
        code = code.toUpperCase();
        String json = null;
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        //验证码过期
        if (jwtEmailHelper.isExpiration(token)){
            Result result = Result.fail(-1, "验证码过期");
            json = objectMapper.writeValueAsString(result);
            response.getWriter().print(json);
            return false;
        }
        //验证码错误
        else if (!jwtEmailHelper.getEmailCode(token).equals(code)){
            Result result = Result.fail(-1, "验证码错误");
            json = objectMapper.writeValueAsString(result);
            response.getWriter().print(json);
            return false;
        }

        return true;
    }
}
